package Service;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.List;

import javax.persistence.EntityManager;

import DAO.DateDAO;
import DAO.QuoteDAO;
import DAO.StockDAO;
import Entity.Date;
import Entity.Quote;
import Entity.Stock;
import Helpers.QuoteHelper;
import Helpers.StockHelper;
import VOs.QuoteVO;
import VOs.StockVO;

public class QuoteService {

	public void create(QuoteVO companyVo, EntityManager em) {
		Quote quote = new QuoteHelper().toEntity(companyVo);
		Calendar calendar = GregorianCalendar.getInstance();
		if(companyVo.getDate() == null){
			Date date = new Date();
			date.setDay(calendar.get(Calendar.DAY_OF_MONTH));
			date.setMonth(calendar.get(Calendar.MONTH));
			date.setYear(calendar.get(Calendar.YEAR));
			DateDAO.create(date, em);
			quote.setDate(date);
		}
		QuoteDAO.create(quote, em);
	}

	public List<QuoteVO> readQuoter(StockVO companyVo, EntityManager em) {
		Stock stock = new StockHelper().toEntity(companyVo);
		List<Quote> quotes = StockDAO.read(stock, em).getQuotes();
		List<QuoteVO> quotesVo = new ArrayList<QuoteVO>(quotes.size());
		for (Quote quote : quotes) {
			quotesVo.add(quote.tovo());
		}
		return quotesVo;
	}

	public void update(QuoteVO companyVo, QuoteVO newOne, EntityManager em) {
		Quote quote = new QuoteHelper().toEntity(companyVo);
		QuoteDAO.update(quote, em);
	}

	public void delete(QuoteVO companyVo, EntityManager em) {
		Quote quote = new QuoteHelper().toEntity(companyVo);
		QuoteDAO.delete(quote, em);
	}

}
